<?php

declare(strict_types=1);

namespace app\index\controller;

use app\common\tool\Result;
use think\facade\View;
use think\Response;
use app\common\model\Merchant as MerchantModel;
use app\common\model\Product;
use app\common\model\OrderTemporary;
use think\exception\ValidateException;
use app\common\model\Assets;


class Merchant extends Base
{
    /**首页 */
    public function index()
    {
        $info = MerchantModel::where('uid', $this->user->id)->find();

        View::assign([
            'info' => $info,
            'system' => $this->system,
            'uid' => $this->user->id
        ]);
        return View::fetch();
    }
    public function getList(): Response
    {
        $map = ['uid' => $this->user->id];
        return Result::fastReturn(MerchantModel::getPageList($map, '*', $this->getPage(), 20, false));
    }
    /**
     * 入驻提交
     */
    public function save(): Response
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'Merchant');
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }
        return Result::fastReturn(MerchantModel::add($param, $this->user));
    }
    /**
     * 商家管理
     */
    public function management()
    {
        $info = MerchantModel::where(['uid' => $this->user->id, 'status' => 2])->find();
        if (empty($info)) return redirect(url('user/index')->build());
        View::assign('assets', Assets::getFields(3));
        return View::fetch();
    }
    /**
     * 商品列表
     */
    public function shop_index()
    {

        $keyword = $this->request->get('keyword');
        View::assign([
            'keyword' => $keyword
        ]);
        return View::fetch();
    }
    /**
     * 获取商家商品
     */
    public function getShopList()
    {
        $param = $this->request->get();
        $info = MerchantModel::where(['uid' => $this->user->id, 'status' => 2])->find();
        if (empty($info)) return redirect(url('user/index')->build());
        $map[] = ['merchant_id', '=', $info->id];
        $map[] = ['shop_type', '=', 2];
        $like = [];
        if (isset($param['keyword']) && $param['keyword']) {
            $like['field'] = 'title';
            $like['keyword'] = $param['keyword'];
        }
        $list = Product::getPageList($map, 'id,title,price,vip_price,icon,sales,status,is_audit', $param['page'], 20, false, '', '', ['key' => 'sort', 'value' => 'asc'], $like);
        return Result::fastReturn($list);
    }
    /**
     * 删除商品
     */
    public function del()
    {
        return Result::fastReturn(Product::productDelete($this->request->post(), $this->user));
    }
    /**
     * 上下架商品
     */
     public function racks()
     {
         return Result::fastReturn(Product::productRacks($this->request->post()));
     }
    /**
     * 添加
     */
    public function add()
    {
        $merchant = MerchantModel::where(['uid' => $this->user->id, 'status' => 2])->find();
        if (empty($merchant)) return redirect(url('user/index')->build());
        View::assign('cate', self::getCate());
        View::assign('merchant', $merchant);
        return View::fetch('merchant/edit');
    }
    /**
     * 编辑
     */
    public function edit()
    {
        $id = $this->request->param('id', 0);
        $info = Product::where('id', $id)->find();
        $merchant = MerchantModel::where(['uid' => $this->user->id, 'status' => 2])->find();
        if (empty($merchant)) return redirect(url('user/index')->build());
        View::assign('cate', self::getCate());
        View::assign('info', $info);
        View::assign('merchant', $merchant);
        return View::fetch('merchant/edit');
    }
    public static function getCate(): array
    {
        return \app\common\model\ProductCate::where('pid', 2)->field('id,title')->with('child')->select()->toArray();
    }

    public function getCateSelect()
    {
        $id = $this->request->param('id', 0);
        return json(\app\common\model\ProductCate::getCate($id));
    }
    /**
     * 商家添加商品
     */
    public function saveProduct()
    {
        $param = $this->request->post();
        $param['merchant_bl'] = $param['merchant_bl']/100;
        $param['tp_1'] = $param['tp_1']/100;
        $param['tp_2'] = $param['tp_2']/100;
        $param['service_1'] = $param['service_1']/100;
        $param['service_2'] = $param['service_2']/100;
        $param['service_3'] = $param['service_3']/100;
        return Result::fastReturn(Product::saveProduct($param));
    }
    /**
     * 商家订单
     */

    public function my_order()
    {
        return View::fetch();
    }
    /**
     * 订单详情
     */
    public function my_order_details()
    {
        $info = OrderTemporary::where(['id' => $this->request->get('id')])
            ->withoutField('update_time')
            ->with(['productsField', 'p', 'c', 'd', 'express'])
            ->find();
        if (empty($info)) return redirect('/');
        $info->statusCode = $info->getData('status');
        $info->friendlyText = getProductOrderFriendly($info->statusCode);
        View::assign('info', $info);
        return View::fetch();
    }
    /**
     * 发货订单详情
     */
    public function deliver_order_details()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            try {
                $this->validate($param, 'OrderDeliver');
            } catch (ValidateException $e) {
                return Result::fail( $e->getError());
            }
            return Result::fastReturn(OrderTemporary::deliverMerchant($param, $this->user));
        }

        $info = OrderTemporary::where(['id' => $this->request->get('id')])
            ->withoutField('update_time')
            ->with(['productsField', 'p', 'c', 'd', 'express'])
            ->find();
        if (empty($info)) return redirect('/');
        $info->statusCode = $info->getData('status');
        $info->friendlyText = getProductOrderFriendly($info->statusCode);

        View::assign([
            'express' => \app\common\model\Express::where(['status' => 1])->select(),
            'info'    => $info
        ]);
        return View::fetch();
    }

    /**
     * 获取商家订单列表数据
     */
    public function getOrderList(): Response
    {
        try {
            $param = $this->request->get();
            $merchant = MerchantModel::where(['uid' => $this->user->id, 'status' => 2])->find();
            if (empty($merchant)) return redirect(url('user/index')->build());
            $map[] = ['merchant_id', '=', $merchant['id']];
            if (isset($param['type']) && $param['type']) {
                $map[] = ['status', '=', $param['type']];
            }

            $list = OrderTemporary::getPageList(
                $map,
                'id,sn,total_amount,real_amount,create_time,status,shop_type',
                $this->getPage(),
                $this->getLimit(),
                false,
                ['productsField']
            );

            foreach ($list['data'] as &$v) {
                $v->statusCode = $v->getData('status');
            }
            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}
